package com.longge.wechat.message.entity;

import java.util.Date;







import com.longge.wechat.message.wxUtil.WeiXinUtil;
import com.longge.wechat.utils.ReadProperties;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;

/**
 * 微信通用接口凭证
 * 
 * @author ywl
 * @date 2013-12-17
 */
public class AccessToken {
	private static AccessToken accessToken =null;
	// 获取到的凭证
	private static String token;
	// 凭证有效时间，单位：秒
	private static int expiresIn;
	private static long time;
	private long LIMIT = 60*1000*40;// 40个小时获取一次
	public final static String access_token_url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

	private AccessToken(){
		getAccessToken();
	}
	public static void getAccessToken(){
		String requestUrl = access_token_url.replace("APPID", ReadProperties.loadProperties().getProperty("APPID"))
				.replace("APPSECRET", ReadProperties.loadProperties().getProperty("APPSECRET"));
		JSONObject jsonObject = WeiXinUtil.httpRequest(requestUrl, "GET", null);
		// 如果请求成功
		if (null != jsonObject) {
			try {
				token=jsonObject.getString("access_token");
				expiresIn=jsonObject.getInt("expires_in");
				time = new Date().getTime();
			} catch (JSONException e) {
				accessToken = null;
				// 获取token失败
				System.out.println("获取token失败 errcode:{"+jsonObject.getInt("errcode")+"}errmsg:{"+ jsonObject.getString("errmsg")+"}");
			}
		}
	}
	public static AccessToken getInstance() {
		 if(accessToken==null){
			 accessToken = new AccessToken();
		 }
		return accessToken;
	}
	
	public synchronized String ReGetToken(){
		getAccessToken();
		return token;
	}
	public synchronized void  error(int errorCode){
			getAccessToken();
		System.out.println("access 重新获取");
		
	}
	public synchronized String getToken() {
		Date nowDate  = new Date();
		long now = nowDate.getTime();
		if(now-time > LIMIT) {
			getAccessToken();
		}
		return token;
	}
	@SuppressWarnings("static-access")
	public void setToken(String token) {
		this.token = token;
	}
	public int getExpiresIn() {
		return expiresIn;
	}
	@SuppressWarnings("static-access")
	public void setExpiresIn(int expiresIn) {
		this.expiresIn = expiresIn;
	}
	
}
